package org.jeecg.codegeneweb.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileSplitter {

    public static void main(String[] args) {
        File inputFile = new File("path/to/your/input/file.java");

        try {
            new FileSplitter().splitFileAndDeleteOriginal(inputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void splitFileAndDeleteOriginal(File inputFile) throws IOException {
        List<FileContent> fileContents = new ArrayList<>();
        List<String> currentFileContent = new ArrayList<>();
        String currentFileName = null;
        String outputDirectory = inputFile.getParent();

        try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("#segment#")) {
                    if (currentFileName != null) {
                        fileContents.add(new FileContent(currentFileName, currentFileContent));
                        currentFileContent = new ArrayList<>();
                    }
                    currentFileName = line.substring("#segment#".length()).trim();
                } else {
                    currentFileContent.add(line);
                }
            }
            if (currentFileName != null && !currentFileContent.isEmpty()) {
                fileContents.add(new FileContent(currentFileName, currentFileContent));
            }
        }

        if (fileContents.isEmpty()) {
            System.out.println("No segment markers found in the input file.");
            return;
        }

        for (FileContent fileContent : fileContents) {
            File outputFile = new File(outputDirectory, fileContent.fileName);
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
                for (String contentLine : fileContent.content) {
                    writer.write(contentLine);
                    writer.newLine();
                }
            }
        }

        // 删除原始文件
        if (!inputFile.delete()) {
            System.out.println("Failed to delete the original file: " + inputFile.getAbsolutePath());
        } else {
            System.out.println("Original file deleted successfully.");
        }

        System.out.println("Files have been split successfully.");
    }

    private static class FileContent {
        String fileName;
        List<String> content;

        FileContent(String fileName, List<String> content) {
            this.fileName = fileName;
            this.content = content;
        }
    }
}
